package cn.edik;


import org.apache.ftpserver.ConnectionConfig;
import org.apache.ftpserver.ConnectionConfigFactory;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.AnonymousAuthentication;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.apache.ftpserver.usermanager.impl.WritePermission;

import java.util.ArrayList;
import java.util.List;

public class FTP {
    private static FtpServer ftpServer;

    public static void start(int port, String username, String password, String dirPath) {
        int PORT = 21;
        String USERNAME = "anonymous";
        String PASSWORD = "";
        try {
            // 用于创建server
            FtpServerFactory serverFactory = new FtpServerFactory();
            // 配置信息，如设监听的端口，设置IP过滤器
            ListenerFactory listenerFactory = new ListenerFactory();
            // 设置端口
            listenerFactory.setPort(port);
            // 如果五分钟还没任何操作，关闭连接
            // listenerFactory.setIdleTimeout(5*60*1000);

            // 设置匿名用户 但是对于稳健权限是只读

            // 设置用户名密码
            BaseUser user = new BaseUser();
            user.setName(username);
            if (!"".equals(password)) {
                user.setPassword(password);
            }


            // 设置PC端登录后可访问的根目录
            user.setHomeDirectory(dirPath);

            // 授予用户写权限
            List<Authority> authorities = new ArrayList<Authority>();
            authorities.add(new WritePermission());

            user.setAuthorities(authorities);
            serverFactory.getUserManager().save(user);


            // 创建并监听网络
            serverFactory.addListener("default", listenerFactory.createListener());

//            ConnectionConfigFactory connectionConfigFactory = new ConnectionConfigFactory();
//            connectionConfigFactory.setMaxLogins(100);
//            connectionConfigFactory.setMaxThreads(1000);
//            ConnectionConfig connectionConfig = connectionConfigFactory.createConnectionConfig();
//            serverFactory.setConnectionConfig(connectionConfig);

            // 创建服务
            ftpServer = serverFactory.createServer();

            // 开启服务
            ftpServer.start();

            System.out.println("FTP服务启动成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void stop() {
        if (null != ftpServer) {
            ftpServer.stop();
            System.out.println("FTP服务关闭成功");
        } else {
            System.out.println("FTP服务未启动不用关闭");

        }

    }
}
